<template>
  <div class="home-page">
    <div class="container">
      <!-- 轮播图展示 -->
      <div class="banner-section">
        <el-carousel height="300px">
          <el-carousel-item v-for="banner in banners" :key="banner.id">
            <div class="banner-item" :style="{backgroundImage: `url(${banner.img})`}">
              <div class="banner-content">
                <h3 class="banner-title">{{ banner.title }}</h3>
                <p class="banner-desc">{{ banner.description }}</p>
              </div>
            </div>
          </el-carousel-item>
        </el-carousel>
      </div>

      <!-- 分类导航 -->
      <div class="category-section">
        <div class="category-tags">
          <div 
            class="category-tag" 
            :class="{ active: currentCategory === 0 }" 
            @click="handleCategoryChange(0)">全部</div>
          <div 
            v-for="category in categories" 
            :key="category.id" 
            class="category-tag" 
            :class="{ active: currentCategory === category.id }" 
            @click="handleCategoryChange(category.id)">
            {{ category.name }}
          </div>
        </div>
      </div>

      <!-- 热门推荐 -->
      <div class="hot-section" v-if="filteredHotArticles.length > 0">
        <div class="section-header">
          <h2 class="section-title">精选推荐</h2>
        </div>
        <div class="hot-grid">
          <div v-for="item in filteredHotArticles" :key="item.id" class="hot-item card article-card" @click="goToDetail(item.id)">
            <div class="hot-image" :style="{backgroundImage: `url(${item.img})`}"></div>
            <div class="hot-content">
              <h3 class="article-title">{{ item.title }}</h3>
              <!-- <p class="article-summary">{{ item.summary }}</p> -->
              <div class="article-meta">
                <span><el-icon><View /></el-icon> {{ item.views }}</span>
                <span><el-icon><Star /></el-icon> {{ item.likes }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 最新推荐 -->
      <div class="new-section">
        <div class="section-header">
          <h2 class="section-title">{{ currentCategory === 0 ? '最新发布' : getCategoryName(currentCategory) }}</h2>
        </div>
        
        <!-- 文章列表 -->
        <div class="article-list">
          <div 
            v-for="article in filteredArticles" 
            :key="article.id" 
            class="article-item card" 
            @click="goToDetail(article.id)">
            <div class="article-main">
              <div class="article-info">
                <h3 class="article-title">{{ article.title }}</h3>
                <p class="article-summary">{{ article.summary }}</p>
                <div class="article-meta">
                  <span class="author">
                    <el-avatar :size="20" :src="article.avatar  || userAvatar"></el-avatar>
                    {{ article.nickName }}
                  </span>
                  <span><el-icon><Timer /></el-icon> {{ article.publishTime }}</span>
                  <span><el-icon><View /></el-icon> {{ article.views }}</span>
                  <span><el-icon><Star /></el-icon> {{ article.likes }}</span>
                </div>
              </div>
              <div class="article-cover" v-if="article.img">
                <img :src="article.img" :alt="article.title">
              </div>
            </div>
          </div>
        </div>

        <!-- 分页组件 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[5, 10, 15, 20]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            background
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { View, Star, Timer } from '@element-plus/icons-vue'
import request from '@/utils/request'

const userAvatar = ref('https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png')
const router = useRouter()
const banners = ref([])
const hotArticles = ref([])
const articles = ref([])

// 数据
const currentCategory = ref(0) // 0表示全部
// 分页相关数据
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const loading = ref(false)

// 获取分类列表
const fetchCategories = async () => {
  try {
    const res = await request.get('/categories/list')
    
    if (res.data.code === '200') {
      categories.value = res.data.data || []
    } else {
      console.error('获取分类列表失败:', res.data.msg)

    }
  } catch (error) {
    console.error('获取分类列表出错:', error)
  }
}
const categories = ref([
  { id: 1, name: '科技' },
  { id: 2, name: '娱乐' },
  { id: 3, name: '体育' },
  { id: 4, name: '国际' },
  { id: 5, name: '财经' },
  { id: 6, name: '教育' },
  { id: 7, name: '文化' },
  { id: 8, name: '动漫' }
])

//轮播图
const bannersAll = async() => {
  const res = await request.get('/banners/list')
  banners.value = res.data.data
}

//热门推荐
const hotArticlesAll = async() => {
  const res = await request.get('/articles/randomList')
  hotArticles.value = res.data.data
}

//最新发布 - 分页获取
const fetchArticles = async() => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value
    }
    
    // 如果选择了分类，添加分类参数
    if (currentCategory.value !== 0) {
      params.categoryId = currentCategory.value
    }else{
      params.categoryId = 0
    }
    
    const res = await request.get('/articles/page', { params })
    
    console.log('--',res.data.code);
    
    if (res.data.code === '200') {
      articles.value = res.data.data.records || []
      total.value = res.data.data.total || 0
    } else {
      ElMessage.error(res.data.msg || '获取文章列表失败')
    }
  } catch (error) {
    console.error('获取最新文章出错:', error)
    ElMessage.error('获取文章列表失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 生命周期钩子
onMounted(() => {
  bannersAll()
  hotArticlesAll()
  fetchArticles()
  fetchCategories()
})

// 监听分页参数变化，重新获取数据
watch([currentPage, pageSize], () => {
  fetchArticles()
})

// 计算属性
const filteredArticles = computed(() => {
  return articles.value
})

const filteredHotArticles = computed(() => {
  if (currentCategory.value === 0) {
    return hotArticles.value
  } else {
    return hotArticles.value.filter(article => article.categoryId === currentCategory.value)
  }
})

// 方法
const getCategoryName = (id) => {
  const category = categories.value.find(item => item.id === id)
  return category ? category.name : '未分类'
}

const goToDetail = (id) => {
  router.push(`/detail/${id}`)
}

// 分页大小改变
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1 // 重置为第一页
}

// 当前页改变
const handleCurrentChange = (page) => {
  currentPage.value = page
  window.scrollTo(0, 0) // 返回页面顶部
}

// 分类切换
const handleCategoryChange = (categoryId) => {
  if (currentCategory.value === categoryId) return
  currentCategory.value = categoryId
  currentPage.value = 1 // 重置为第一页
  fetchArticles() // 重新获取文章列表
}
</script>

<style scoped>
.home-page {
  padding-bottom: 30px;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 15px;
}

.banner-section {
  margin-bottom: 30px;
}

.banner-item {
  width: 100%;
  height: 100%;
  background-size: cover;
  background-position: center;
  position: relative;
  border-radius: 8px;
  overflow: hidden;
}

.banner-item::before {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 50%;
  background: linear-gradient(to top, rgba(0,0,0,0.7), transparent);
}

.banner-content {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  padding: 20px;
  color: #fff;
}

.banner-title {
  font-size: 24px;
  margin-bottom: 10px;
}

.banner-desc {
  font-size: 16px;
  opacity: 0.9;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-title {
  font-size: 22px;
  font-weight: bold;
  position: relative;
  padding-left: 15px;
}

.section-title::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 5px;
  height: 20px;
  background-color: #409eff;
  border-radius: 3px;
}

.hot-section {
  margin-bottom: 30px;
}

.hot-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20px;
}

.hot-item {
  height: 300px;
  display: flex;
  flex-direction: column;
}

.hot-image {
  flex: 1;
  background-size: cover;
  background-position: center;
  border-top-left-radius: 8px;
  border-top-right-radius: 8px;
}

.hot-content {
  padding: 15px;
}

.card {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.06);
  transition: all 0.3s;
  cursor: pointer;
}

.card:hover {
  box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.1);
}

.article-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.article-item {
  padding: 15px;
}

.article-main {
  display: flex;
  gap: 20px;
}

.article-info {
  flex: 1;
}

.article-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 8px;
  color: #333;
}

.article-summary {
  color: #666;
  margin-bottom: 10px;
  line-height: 1.6;
}

.article-meta {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  font-size: 13px;
  color: #999;
}

.article-meta > span {
  display: flex;
  align-items: center;
  margin-right: 15px;
  margin-bottom: 5px;
}

.article-meta .el-icon {
  margin-right: 5px;
}

.article-cover {
  width: 200px;
  height: 120px;
  overflow: hidden;
  border-radius: 4px;
}

.article-cover img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s;
}

.article-item:hover .article-cover img {
  transform: scale(1.05);
}

.author {
  display: flex;
  align-items: center;
  gap: 5px;
}

.pagination-container {
  margin-top: 30px;
  display: flex;
  justify-content: center;
}

.category-section {
  margin-bottom: 30px;
}

.category-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.category-tag {
  padding: 8px 16px;
  border-radius: 20px;
  background-color: #f4f4f5;
  color: #606266;
  cursor: pointer;
  transition: all 0.3s;
}

.category-tag:hover {
  background-color: #e6f1fc;
  color: #409eff;
}

.category-tag.active {
  background-color: #409eff;
  color: #fff;
}

/* 响应式调整 */
@media screen and (max-width: 768px) {
  .hot-grid {
    grid-template-columns: 1fr;
  }
  
  .article-main {
    flex-direction: column;
  }
  
  .article-cover {
    width: 100%;
    height: 180px;
    margin-top: 10px;
  }

  .pagination-container {
    overflow-x: auto;
  }
}
</style> 